<template>
  <div>
    <van-uploader
      v-model="fileList"
      :max-count="maxCount"
      :before-read="beforeRead"
      :after-read="afterRead"
      :disabled="disabled"
      @delete="deleteAction"
    />
  </div>
</template>

<script>
import { Notify, Toast } from 'vant'
import { getFileSign, uploadFile } from '@/api/school'
import lrz from 'lrz'

export default {
  name: 'UploadImg',
  props: {
    defaultStringList: {
      type: String,
      default: () => {
        return ''
      },
    },
    rootDir: {
      type: String,
      default: () => {
        return 'toilet'
      },
    },
    fileDir: {
      type: String,
      default: () => {
        return 'image'
      },
    },
    uploadType: {
      type: String,
      default: () => {
        return 'hadoop'
      },
    },
    format: {
      type: Array,
      default: () => {
        return ['jpg', 'jpeg', 'png']
      },
    },
    maxSize: {
      type: Number,
      default: () => {
        return 20
      },
    },
    maxCount: {
      type: Number,
      default: () => {
        return 100
      },
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false
      },
    },
  },
  model: {
    prop: 'defaultStringList',
    event: 'change',
  },
  data() {
    return {
      fileList: [],
      upPicData: {
        file: '',
        filePath: '',
        fileName: '',
      },
    }
  },
  computed: {
    getDefaultList() {
      if (this.defaultStringList !== '') {
        let list = this.defaultStringList.split(',')
        let data = []
        list.forEach((item, index) => {
          if (item !== '') {
            data.push({ name: this.getUrlImgName(item), url: item })
          }
        })
        return data
      }
      return []
    },
  },
  methods: {
    beforeRead(file) {
      // 校验上传数量
      if (this.maxCount && this.fileList.length >= this.maxCount) {
        Toast('请上传小于' + this.maxCount + '张图片')
        return false
      }
      // 校验文件大小
      if (file.size > this.maxSize * 1024 * 1024) {
        Toast('请上传小于' + this.maxSize + 'M的图片！')
        return false
      }
      // 文件格式校验
      if (this.format.length) {
        const _file_format = file.name.split('.').pop().toLocaleLowerCase()
        const checked = this.format.some(
          (item) => item.toLocaleLowerCase() === _file_format
        )
        if (!checked) {
          Toast('请上传 ' + this.format.join(',') + ' 格式图片')
          return false
        }
      }
      // return true
      return !this.maxCount || this.fileList.length < this.maxCount
    },
    // 返回 Promise
    afterRead(file, detail) {
      file.status = 'uploading'
      file.message = '上传中...'
      // 处理
      if (this.uploadType === 'hadoop') {
        lrz(file.file, { quality: 0.1 }).then((res) => {
          let index = res.base64.indexOf('base64,') + 7
          this.upPicData.file = res.base64.substring(index)
          this.upPicData.filePath = this.rootDir + '/' + this.fileDir
          this.upPicData.fileName = file.file.name
          this.getHaDoopSign(res, this.upPicData.file)
          return false
        })
        // let index = file.content.indexOf('base64,') + 7
        // this.upPicData.file = file.content.substring(index)
        // this.upPicData.filePath = this.rootDir + '/' + this.fileDir
        // this.upPicData.fileName = file.file.name
        // this.getHaDoopSign(file, this.upPicData.file)
        // return false
      }
    },
    async getHaDoopSign(file, base64File) {
      let data = {
        timestamp: new Date().getTime(),
        fileName: this.upPicData.fileName,
        filePath: this.upPicData.filePath,
      }
      let count = this.fileList.length - 1
      const res = await getFileSign(data)
      if (res.data.errcode == 0) {
        data.sign = res.data.data.sign
        this.useJavaUpImg(
          base64File,
          data,
          res.docking_url ? res.docking_url : false,
          count,
          file
        )
      }
    },
    async useJavaUpImg(base64File, data, url, count, file) {
      data.file = base64File
      let apiUrl = uploadFile
      if (url) {
        apiUrl = url
      }
      const res = await apiUrl(data)
      if (res.data.errcode == 0) {
        this.fileList[count] = {
          url: res.data.data,
        }
        file.status = ''
        Toast('上传成功')
        this.resultAction(this.fileList)
      }
    },
    resultAction(data) {
      let result = ''
      if (data.length > 0) {
        if (this.maxCount > 1) {
          data.forEach((item) => {
            result += item.url + ','
          })
        } else {
          result = data[0].url.replace(
            'http://10.195.107.22:9864',
            'http://daliandl.lngov.top'
          )
        }
      }
      this.$emit('change', result)
      this.$emit('result', result)
    },
    getUrlImgName(url) {
      let pos = url.lastIndexOf('/')
      if (pos === -1) {
        pos = url.lastIndexOf('\\')
      }
      let filename = url.substr(pos + 1)
      if (filename.indexOf('?') !== -1) {
        let arr = filename.split('?')
        filename = arr[0]
      }
      return filename
    },
    deleteAction(file) {
      console.log('===', file)
      this.resultAction(this.fileList)
    },
  },
  watch: {
    defaultStringList(data) {
      this.$nextTick(() => {
        this.fileList = this.getDefaultList
      })
    },
  },
  mounted() {
    this.fileList = this.getDefaultList
  },
}
</script>

<style scoped></style>
